package com.tree.jobquartz.template;

import com.tree.jobquartz.detail.JobDetailManager;
import com.tree.jobquartz.trigger.TriggerManager;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @ClassName QuartzTemplate
 * @Description: 定时任务调度器模板方法
 * @Author: myl
 * @create_time: 2020/10/23 09:24
 */
@Component
@Slf4j
public class SchedulerTemplate {

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private JobDetailManager jobDetailManager;

    @Autowired
    private TriggerManager triggerManager;

    /**
     * 开启回测定时任务
     *
     * @param backTestId
     * @param jobClass
     * @throws SchedulerException
     */
    public void startBackTestJob(String backTestId, String requestId, String resultId, String uId,
                                 Class<? extends Job> jobClass) {
        // 添加定时任务
        JobDetail jobDetailInstance = jobDetailManager.getBackTestJobDetailInstance(backTestId, jobClass);
        Trigger triggerInstance = triggerManager.getBackTestTriggerInstance(backTestId, requestId, resultId, uId);

        try {
            scheduler.scheduleJob(jobDetailInstance, triggerInstance);
            if (!scheduler.isShutdown()) {
                // 开启任务
                scheduler.start();
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
            log.error("创建查询回测结果的定时任务出现异常，回测Id为{}", backTestId);
        }
    }


    /**
     * 暂停任务
     *
     * @param identity
     */
    public void shutdown(String identity) {
        try {
            // 暂停Trigger
            scheduler.pauseTrigger(TriggerKey.triggerKey(identity));
        } catch (SchedulerException e) {
            e.printStackTrace();
            log.info("------------不好意思，暂停job报错了,错误信息为：" + e.getMessage());
        }
    }

    /**
     * 恢复job
     *
     * @param identity
     * @throws SchedulerException
     */
    public void resume(String identity) {
        try {
            // 恢复触发器
            scheduler.resumeTrigger(TriggerKey.triggerKey(identity));
        } catch (SchedulerException e) {
            e.printStackTrace();
            log.info("------------不好意思，恢复job报错了,错误信息为：" + e.getMessage());
        }
    }

    /**
     * 从调度中心删除job
     *
     * @param identity
     *            认证身份
     * @throws SchedulerException
     */
    public void del(String identity) {
        try {
            // 暂停触发器
            scheduler.pauseTrigger(TriggerKey.triggerKey(identity));
            // 移除触发器
            scheduler.unscheduleJob(TriggerKey.triggerKey(identity));
            // 删除Job
            scheduler.deleteJob(JobKey.jobKey(identity));
        } catch (SchedulerException e) {
            e.printStackTrace();
            log.info("------------不好意思，删除job报错了,错误信息为：" + e.getMessage());
        }
    }

}
